package com.opengate.demo.api.biz.test.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.opengate.base.authtoken.AuthTokenHelper;
import com.opengate.base.authtoken.JwtHelper;
import com.opengate.base.constants.AppConstants;
import com.opengate.base.currentuser.model.CurrentUserDto;
import com.opengate.base.oss.helper.OssHelper;
import com.opengate.demo.api.base.cache.DemoCache;
import com.opengate.demo.api.base.mq.DemoSendMq;
import com.opengate.demo.api.biz.test.mapper.UserMapper;
import com.opengate.demo.api.biz.test.model.entity.UserEntity;
import com.opengate.demo.api.biz.test.service.UserService;
import com.opengate.demo.contact.message.DemoMessage;
import com.opengate.demo.contact.req.GetDemoInfoReq;
import com.opengate.demo.contact.resp.GetDemoInfoResp;
import com.opengate.demo.contact.resp.UserLoginResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;

/**
 * 用户表 服务实现类
 *
 * @author 曳戈泰尔
 * @since 2023-04-27
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    /** 注入缓存 */
    private DemoCache demoCache;

    @Autowired
    public void setDemoCache(DemoCache demoCache) {
        this.demoCache = demoCache;
    }

    /** 注入mq */
    private DemoSendMq demoSendMq;

    @Autowired
    public void setDemoSendMq(DemoSendMq demoSendMq) {
        this.demoSendMq = demoSendMq;
    }

    /** 注入线程池 */
    private Executor threadPoolExecutor;

    @Autowired
    public void setThreadPoolExecutor(Executor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    /** 注入OSS */
    private OssHelper ossHelper;

    @Autowired
    public void setOssHelper(OssHelper ossHelper) {
        this.ossHelper = ossHelper;
    }

    @Override
    public UserLoginResp userLogin(GetDemoInfoReq req) {

        // 查询用户信息
        int id = 1;
        UserEntity user = this.getById(id);

        // 获取用户登录Token
        Map<String, Object> claims = new HashMap<>();
        claims.put("userInfo", user);
        claims.put(AppConstants.USER_ID, user.getId());
        String token = JwtHelper.createToken(claims);

        // 设置登录信息到Redis
        AuthTokenHelper.setAuthToken(user.getId().toString(), System.currentTimeMillis(), token);

        // 返回登录信息
        return UserLoginResp.builder().userId(user.getId().toString()).token(token).build();
    }

    @Override
    public GetDemoInfoResp getDemoInfo(GetDemoInfoReq req) {

        // 查询用户信息
        int id = 1;
        UserEntity user = this.getById(id);

        // 缓存用户信息
        // 查询缓存打印
        demoCache.cacheUser(id, JSON.toJSONString(user));
        String str = demoCache.getUserCache(id);
        log.info("str={}", str);

        // 发送消息
        DemoMessage demoMessage = new DemoMessage().setUserId(id).setAuditType(11);
        demoSendMq.sendDemoMessage(demoMessage);
        log.info("已发消息demoMessage={}", demoMessage);

        demoSendMq.sendRepDemoMessage(demoMessage);
        log.info("已发消息sendRepDemoMessage={}", demoMessage);

        return new GetDemoInfoResp().setMobile(req.getMobile());
    }

    @Override
    public String test(CurrentUserDto currentUser) {

        int id = 1;
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            String a = demoCache.getUserCache(id);
            log.info("a={}，thread={}", a, Thread.currentThread().getName());
        }
        log.info("test costTime={}", System.currentTimeMillis() - startTime);

        // 测试线程池
        startTime = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            threadPoolExecutor.execute(
                    () -> {
                        String a = demoCache.getUserCache(id);
                        log.info("a={}，thread={}", a, Thread.currentThread().getName());
                        countDownLatch.countDown();
                    });
        }
        try {
            countDownLatch.await();
            log.info("test costTime={}", System.currentTimeMillis() - startTime);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return currentUser.getUserId().toString();
    }

    @Override
    public String testDeferred() {

        String url = "https://file.folkspace.cn/source/b92e9de3-72e3-4e1b-84c7-877ebd100bf9.jpeg";

        // 测试OSS
        return ossHelper.uploadFile2OSS(url);
    }
}
